package dice.sinanya.db.lastMessages;

import dice.sinanya.db.tools.SqliteUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.*;

public class InsertLastMessages {
    private static final Logger logger = LogManager.getLogger(InsertLastMessages.class.getName());
    SqliteUtil sqliteUtil;
    Connection connection;
    int len = 80;

    public InsertLastMessages() {
        sqliteUtil = new SqliteUtil();
        initCon();
        initDb();
    }

    private void initCon() {
        do {
            connection = sqliteUtil.getDiceLogConnection();
        } while (connection == null);
    }

    private void initDb() {
        try (Statement statement = connection.createStatement()) {
            statement.executeUpdate("create table if not exists lastMessages(groupId long,time datetime,PRIMARY KEY (groupId));");
        } catch (SQLException sqlException) {
            logger.error(sqlException.getMessage(), sqlException);
        }
    }


    public void insert(long group) {
        try {
            if (connection == null || connection.isClosed()) {
                initCon();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //language=SQLite
        String sql = "replace into lastMessages(groupId,time) values(?,?);";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setLong(1, group);
            statement.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
            statement.executeUpdate();
        } catch (SQLException ignore) {
        }
    }
}
